// store/modules/userInfo.js
import { defineStore } from 'pinia';
import { getAllUsers, getMenus } from '@/api/manager.js';
import { removeTokens } from '@/composables/auth.js';

export const useUserInfoStore = defineStore('userInfo', {
    state: () => ({
        user: [],
        asideWidth: '250px',
        Menus: [],
        ruleNames: [],
    }),
    getters: {
        permissions: (state) => state.ruleNames, // 为 v-permission 提供 getter
    },
    actions: {
        SET_MENUS(menus) {
            this.Menus = menus;
            // 提取权限名称
            const permissions = extractPermissions(menus);
            this.SET_RULENAME(permissions);
        },
        SET_RULENAME(ruleNames) {
            this.ruleNames = ruleNames; // 修复拼写错误
        },
        async getMenus() {
            try {
                const res = await getMenus();
                this.SET_MENUS(res.detail);
                return res;
            } catch (error) {
                console.error('获取菜单失败:', error);
                throw new Error(error);
            }
        },
        SET_USERINFO(user) {
            this.user = user;
        },
        async getUserInfo() {
            try {
                const res = await getAllUsers();
                this.SET_USERINFO(res.detail);
                return res;
            } catch (error) {
                console.error('获取用户信息失败:', error);
                throw new Error(error);
            }
        },
        logouts() {
            removeTokens();
            this.user = [];
            this.Menus = [];
            this.ruleNames = [];
        },
        handleAsideWidth() {
            this.asideWidth = this.asideWidth === '250px' ? '64px' : '250px';
        },
    },
});

// 提取权限的辅助函数
function extractPermissions(menus) {
    const permissions = [];
    const extract = (items) => {
        items.forEach(item => {
            if (item.perms) permissions.push(item.perms);
            if (item.childrenMenus) extract(item.childrenMenus);
        });
    };
    extract(menus);
    return permissions;
}